<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

  <script src="./lib/vue.js"></script>
</body>

</html>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./lib/vue.js"></script>
</head>

<body>
  <div id="app">
    <ul>
      <li v-for="(item,index) in carts" :key="item.id">
        <span>编号：{{item.id}}</span>
        <span>名称：{{item.name}}</span>
        <span>
          <button>-</button>
          <input type="text" v-model.number="item.num" @input="setNum(item)">
          <button @click="add(item)">+</button>
        </span>
        <span>单价：{{item.price}}</span>
        <span>小计：{{item.num*item.price}}</span>
      </li>
    </ul>
    <hr>
    <input type="text" v-model="title">
    <hr>
    <h3>合计：{{getTotalPrice()}}</h3>
    <h3>合计：{{getTotalPrice()}}</h3>
    <h3>计算属性的合计：{{getTotalPriceComputed}}</h3>
    <h3>计算属性的合计：{{getTotalPriceComputed}}</h3>
  </div>

  <script>
    let vm = new Vue({
      el: '#app',
      data: {
        title: '购物车',
        carts: [
          { id: 1, num: 1, price: 1, name: '小米11' },
          { id: 2, num: 2, price: 1, name: '华为p50' },
          { id: 3, num: 3, price: 1, name: 'IQOO7' },
        ]
      },
      // 计算属性 如果你依赖项没有改变，则下次使用它时，会读缓存中的数据，提升性能
      computed: {
        getTotalPriceComputed() {
          /* console.log(1111)
          let total = 0
          this.carts.forEach(item => {
            total += item.price * item.num
          })
          return total */
          return this.carts.reduce((total, item) => total += item.price * item.num, 0) + this.title
        }
      },
      methods: {
        setNum(item) {
          item.num = Math.max(1, Math.min(10, item.num))
        },
        add(item) {
          // item.num = ++item.num > 3 ? 3 : item.num
          item.num = Math.min(10, ++item.num)
        },
        getTotalPrice() {
          // console.log(222)
          let total = 0
          this.carts.forEach(item => {
            total += item.price * item.num
          })
          return total
        }
      }
    })
  </script>
</body>

</html>